<template>
  <div class="profile-page">
    <!-- 顶部导航栏 -->
    <Header />
    
    <div class="main-content">
      <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ $t('nav.profile') }}</h1>
          <p>管理您的个人信息和账户设置</p>
        </div>
        
        <div class="profile-content">
          <!-- 侧边栏导航 -->
          <div class="sidebar">
            <a-menu
              v-model:selectedKeys="selectedMenuKey"
              mode="inline"
              @click="handleMenuClick"
            >
              <a-menu-item key="profile">
                <UserOutlined />
                <span>个人资料</span>
              </a-menu-item>
              <a-menu-item key="orders">
                <ShoppingOutlined />
                <span>{{ $t('nav.orders') }}</span>
              </a-menu-item>
              <a-menu-item key="favorites">
                <HeartOutlined />
                <span>{{ $t('nav.favorites') }}</span>
              </a-menu-item>
              <a-menu-item key="address">
                <EnvironmentOutlined />
                <span>收货地址</span>
              </a-menu-item>
              <a-menu-item key="security">
                <SafetyOutlined />
                <span>账户安全</span>
              </a-menu-item>
              <a-menu-item key="settings">
                <SettingOutlined />
                <span>账户设置</span>
              </a-menu-item>
            </a-menu>
          </div>
          
          <!-- 主内容区域 -->
          <div class="main-panel">
            <!-- 个人资料 -->
            <div v-if="selectedMenuKey.includes('profile')" class="panel-content">
              <h2>个人资料</h2>
              <a-form
                :model="profileForm"
                :rules="profileRules"
                layout="vertical"
                @finish="updateProfile"
              >
                <a-row :gutter="24">
                  <a-col :span="12">
                    <a-form-item label="{{ $t('user.username') }}" name="username">
                      <a-input v-model:value="profileForm.username" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="{{ $t('user.email') }}" name="email">
                      <a-input v-model:value="profileForm.email" />
                    </a-form-item>
                  </a-col>
                </a-row>
                
                <a-row :gutter="24">
                  <a-col :span="12">
                    <a-form-item label="{{ $t('user.phone') }}" name="phone">
                      <a-input v-model:value="profileForm.phone" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="{{ $t('user.gender') }}" name="gender">
                      <a-select v-model:value="profileForm.gender">
                        <a-select-option value="male">{{ $t('user.male') }}</a-select-option>
                        <a-select-option value="female">{{ $t('user.female') }}</a-select-option>
                        <a-select-option value="other">{{ $t('user.other') }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
                
                <a-form-item label="{{ $t('user.birthday') }}" name="birthday">
                  <a-date-picker
                    v-model:value="profileForm.birthday"
                    style="width: 100%"
                  />
                </a-form-item>
                
                <a-form-item label="{{ $t('user.bio') }}" name="bio">
                  <a-textarea
                    v-model:value="profileForm.bio"
                    :rows="4"
                    placeholder="介绍一下自己..."
                  />
                </a-form-item>
                
                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="updating">
                    保存修改
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
            
            <!-- 我的订单 -->
            <div v-if="selectedMenuKey.includes('orders')" class="panel-content">
              <h2>{{ $t('nav.orders') }}</h2>
              <div class="order-list">
                <div v-for="order in mockOrders" :key="order.id" class="order-item">
                  <div class="order-header">
                    <span class="order-id">订单号：{{ order.id }}</span>
                    <span class="order-status" :class="order.status">
                      {{ getOrderStatusText(order.status) }}
                    </span>
                  </div>
                  <div class="order-products">
                    <div v-for="product in order.products" :key="product.id" class="product-item">
                      <img :src="product.images ? product.images[0] : product.image" :alt="product.name" />
                      <div class="product-info">
                        <h4>{{ product.name }}</h4>
                        <p>¥{{ product.price }} × {{ product.quantity }}</p>
                      </div>
                    </div>
                  </div>
                  <div class="order-footer">
                    <span class="order-total">总计：¥{{ order.total }}</span>
                    <div class="order-actions">
                      <a-button size="small" @click="viewOrderDetail(order.id)">
                        查看详情
                      </a-button>
                      <a-button 
                        v-if="order.status === 'pending'" 
                        size="small" 
                        type="primary"
                        @click="payOrder(order.id)"
                      >
                        立即支付
                      </a-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 我的收藏 -->
            <div v-if="selectedMenuKey.includes('favorites')" class="panel-content">
              <h2>{{ $t('nav.favorites') }}</h2>
              <div class="favorites-grid">
                <div v-for="product in mockFavorites" :key="product.id" class="favorite-item">
                  <img :src="product.images ? product.images[0] : product.image" :alt="product.name" />
                  <div class="product-info">
                    <h4>{{ product.name }}</h4>
                    <p class="price">¥{{ product.price }}</p>
                    <div class="actions">
                      <a-button size="small" @click="addToCart(product)">
                        加入购物车
                      </a-button>
                      <a-button size="small" @click="removeFavorite(product.id)">
                        取消收藏
                      </a-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 收货地址 -->
            <div v-if="selectedMenuKey.includes('address')" class="panel-content">
              <h2>收货地址</h2>
              <a-button type="primary" @click="showAddressModal = true" style="margin-bottom: 20px;">
                添加新地址
              </a-button>
              
              <div class="address-list">
                <div v-for="address in mockAddresses" :key="address.id" class="address-item">
                  <div class="address-info">
                    <h4>{{ address.name }} {{ address.phone }}</h4>
                    <p>{{ address.province }} {{ address.city }} {{ address.district }}</p>
                    <p>{{ address.detail }}</p>
                  </div>
                  <div class="address-actions">
                    <a-button size="small" @click="editAddress(address)">
                      编辑
                    </a-button>
                    <a-button size="small" danger @click="deleteAddress(address.id)">
                      删除
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 账户安全 -->
            <div v-if="selectedMenuKey.includes('security')" class="panel-content">
              <h2>账户安全</h2>
              <div class="security-items">
                <div class="security-item">
                  <div class="security-info">
                    <h4>登录密码</h4>
                    <p>定期更换密码可以保护账户安全</p>
                  </div>
                  <a-button @click="showPasswordModal = true">
                    修改密码
                  </a-button>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>手机绑定</h4>
                    <p>已绑定：{{ userInfo.phone || '未绑定' }}</p>
                  </div>
                  <a-button @click="showPhoneModal = true">
                    {{ userInfo.phone ? '更换手机' : '绑定手机' }}
                  </a-button>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>邮箱绑定</h4>
                    <p>已绑定：{{ userInfo.email || '未绑定' }}</p>
                  </div>
                  <a-button @click="showEmailModal = true">
                    {{ userInfo.email ? '更换邮箱' : '绑定邮箱' }}
                  </a-button>
                </div>
              </div>
            </div>
            
            <!-- 账户设置 -->
            <div v-if="selectedMenuKey.includes('settings')" class="panel-content">
              <h2>账户设置</h2>
              <div class="settings-items">
                <div class="setting-item">
                  <div class="setting-info">
                    <h4>消息通知</h4>
                    <p>接收订单状态、促销活动等消息</p>
                  </div>
                  <a-switch v-model:checked="settings.notifications" />
                </div>
                
                <div class="setting-item">
                  <div class="setting-info">
                    <h4>邮件订阅</h4>
                    <p>订阅我们的最新优惠和活动信息</p>
                  </div>
                  <a-switch v-model:checked="settings.emailSubscription" />
                </div>
                
                <div class="setting-item">
                  <div class="setting-info">
                    <h4>隐私保护</h4>
                    <p>允许其他用户查看我的基本信息</p>
                  </div>
                  <a-switch v-model:checked="settings.privacy" />
                </div>
              </div>
              
              <div class="danger-zone">
                <h3>危险操作</h3>
                <a-button danger @click="showDeleteAccountModal = true">
                  删除账户
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部信息 -->
    <Footer />
    
    <!-- 修改密码弹窗 -->
    <a-modal
      v-model:open="showPasswordModal"
      title="修改密码"
      @ok="updatePassword"
    >
      <a-form layout="vertical">
        <a-form-item label="当前密码">
          <a-input-password v-model:value="passwordForm.currentPassword" />
        </a-form-item>
        <a-form-item label="新密码">
          <a-input-password v-model:value="passwordForm.newPassword" />
        </a-form-item>
        <a-form-item label="确认新密码">
          <a-input-password v-model:value="passwordForm.confirmPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 删除账户确认弹窗 -->
    <a-modal
      v-model:open="showDeleteAccountModal"
      title="删除账户"
      @ok="deleteAccount"
    >
      <p>此操作不可逆，确定要删除您的账户吗？</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  UserOutlined,
  ShoppingOutlined,
  HeartOutlined,
  EnvironmentOutlined,
  SafetyOutlined,
  SettingOutlined
} from '@ant-design/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'

// 使用Vuex store和Vue Router
const store = useStore()
const router = useRouter()

// 响应式数据
const selectedMenuKey = ref(['profile'])
const updating = ref(false)
const showPasswordModal = ref(false)
const showDeleteAccountModal = ref(false)
const showAddressModal = ref(false)
const showPhoneModal = ref(false)
const showEmailModal = ref(false)

// 表单数据
const profileForm = reactive({
  username: '',
  email: '',
  phone: '',
  gender: '',
  birthday: null,
  bio: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const settings = reactive({
  notifications: true,
  emailSubscription: false,
  privacy: true
})

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名' },
    { min: 2, max: 20, message: '用户名长度在2-20个字符之间' }
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
  ]
}

// 计算属性
const userInfo = computed(() => store.getters['user/userInfo'])

// 模拟数据 - 将通过API获取
const mockOrders = ref([])
const mockFavorites = ref([])
const mockAddresses = ref([])

// 方法
const handleMenuClick = ({ key }) => {
  selectedMenuKey.value = [key]
}

const updateProfile = async () => {
  updating.value = true
  
  try {
    await store.dispatch('user/updateUserInfo', profileForm)
    message.success('个人资料更新成功')
  } catch (error) {
    message.error('更新失败，请重试')
  } finally {
    updating.value = false
  }
}

const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    delivered: '已送达',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const viewOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

const payOrder = (orderId) => {
  router.push(`/checkout?orderId=${orderId}`)
}

const addToCart = (product) => {
  store.dispatch('cart/addToCart', product)
  message.success('已添加到购物车')
}

const removeFavorite = (productId) => {
  mockFavorites.value = mockFavorites.value.filter(item => item.id !== productId)
  message.success('已取消收藏')
}

const editAddress = (address) => {
  // 实现编辑地址逻辑
  message.info('编辑地址功能开发中')
}

const deleteAddress = (addressId) => {
  mockAddresses.value = mockAddresses.value.filter(item => item.id !== addressId)
  message.success('地址删除成功')
}

const updatePassword = () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    message.error('两次输入的密码不一致')
    return
  }
  
  message.success('密码修改成功')
  showPasswordModal.value = false
  
  // 清空表单
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

const deleteAccount = () => {
  message.success('账户删除成功')
  showDeleteAccountModal.value = false
  store.dispatch('user/logout')
  router.push('/')
}

// 初始化数据
const initProfileData = () => {
  if (userInfo.value) {
    Object.assign(profileForm, {
      username: userInfo.value.username || '',
      email: userInfo.value.email || '',
      phone: userInfo.value.phone || '',
      gender: userInfo.value.gender || '',
      birthday: userInfo.value.birthday ? new Date(userInfo.value.birthday) : null,
      bio: userInfo.value.bio || ''
    })
  }
}

// 生命周期
onMounted(() => {
  // 检查登录状态
  const token = localStorage.getItem('token')
  if (!token) {
    message.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 检查用户信息
  if (!userInfo.value) {
    // 尝试从localStorage获取用户信息
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      try {
        const user = JSON.parse(storedUserInfo)
        store.commit('user/SET_USER_INFO', user)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        message.error('用户信息异常，请重新登录')
        router.push('/login')
        return
      }
    } else {
      message.error('用户信息不存在，请重新登录')
      router.push('/login')
      return
    }
  }
  
  initProfileData()
  
  // 加载模拟数据
  loadMockData()
})

// 加载模拟数据
const loadMockData = () => {
  // 模拟订单数据
  mockOrders.value = [
    {
      id: 'ORD001',
      status: 'completed',
      total: 299.00,
      products: [
        {
          id: 1,
          name: '智能手机',
          price: 299.00,
          quantity: 1,
          images: ['https://picsum.photos/60/60?random=1']
        }
      ]
    },
    {
      id: 'ORD002',
      status: 'pending',
      total: 158.00,
      products: [
        {
          id: 2,
          name: '无线耳机',
          price: 158.00,
          quantity: 1,
          images: ['https://picsum.photos/60/60?random=2']
        }
      ]
    }
  ]
  
  // 模拟收藏数据
  mockFavorites.value = [
    {
      id: 1,
      name: '智能手机',
      price: 299.00,
      images: ['https://picsum.photos/200/150?random=1']
    },
    {
      id: 2,
      name: '无线耳机',
      price: 158.00,
      images: ['https://picsum.photos/200/150?random=2']
    },
    {
      id: 3,
      name: '智能手表',
      price: 899.00,
      images: ['https://picsum.photos/200/150?random=3']
    }
  ]
  
  // 模拟地址数据
  mockAddresses.value = [
    {
      id: 1,
      name: '张三',
      phone: '13800138001',
      province: '北京市',
      city: '北京市',
      district: '朝阳区',
      detail: '三里屯SOHO 1号楼'
    },
    {
      id: 2,
      name: '李四',
      phone: '13800138002',
      province: '上海市',
      city: '上海市',
      district: '浦东新区',
      detail: '陆家嘴金融中心'
    }
  ]
}
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.profile-content {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 20px;
}

.sidebar {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.main-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-content {
  padding: 30px;
}

.panel-content h2 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 30px 0;
}

/* 订单列表样式 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.order-id {
  font-weight: 500;
  color: #333;
}

.order-status {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.order-status.completed {
  background: #f6ffed;
  color: #52c41a;
}

.order-status.pending {
  background: #fff7e6;
  color: #fa8c16;
}

.order-products {
  padding: 20px;
}

.product-item {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-item img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #333;
}

.product-info p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}

.order-total {
  font-weight: 600;
  color: #333;
}

.order-actions {
  display: flex;
  gap: 10px;
}

/* 收藏列表样式 */
.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.favorite-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.favorite-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.favorite-item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.favorite-item .product-info {
  padding: 15px;
}

.favorite-item h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}

.favorite-item .price {
  color: #ff4d4f;
  font-weight: 600;
  margin: 0 0 15px 0;
}

.favorite-item .actions {
  display: flex;
  gap: 10px;
}

/* 地址列表样式 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.address-info h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.address-info p {
  margin: 0 0 5px 0;
  color: #666;
}

.address-info p:last-child {
  margin-bottom: 0;
}

.address-actions {
  display: flex;
  gap: 10px;
}

/* 安全设置样式 */
.security-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.security-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.security-info p {
  margin: 0;
  color: #666;
}

/* 账户设置样式 */
.settings-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 40px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.setting-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.setting-info p {
  margin: 0;
  color: #666;
}

.danger-zone {
  border: 1px solid #ff4d4f;
  border-radius: 8px;
  padding: 20px;
  background: #fff2f0;
}

.danger-zone h3 {
  color: #ff4d4f;
  margin: 0 0 15px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .sidebar {
    order: 2;
  }
  
  .main-panel {
    order: 1;
  }
  
  .panel-content {
    padding: 20px;
  }
  
  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .address-item,
  .security-item,
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .address-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 